<template>
  <div class="home-container">
    <!-- 头部区域 -->
    <van-nav-bar fixed>
      <template #left>
        <img src="../../assets/toutiao_logo.png" alt="logo" class="logo" />
      </template>
      <template #right>
        <van-icon name="search" color="white" size="18" />
      </template>
    </van-nav-bar>

    <!-- 频道列表 -->
    <van-tabs v-model:active="active" sticky offset-top="1.22667rem">
      <van-tab :title="item.name" v-for="item in channels" :key="item.id">
        <!-- 文章列表组件 -->
        <art-list :channel-id="item.id"></art-list>
      </van-tab>
    </van-tabs>

    <!-- 右侧的编辑频道的小图标 -->
    <van-icon name="plus" size="14" class="moreChannels" @click="show = true" />
  </div>

  <!-- 弹出层组件 -->
  <!-- close-on-click-overlay 是否在点击遮罩层后关闭（false 不关闭） -->
  <van-popup v-model:show="show" :close-on-click-overlay="false" teleport="body" position="center" class="popup-home-cover">
    <div class="popup-container">

      <!-- 弹出层的头部区域 -->
      <van-nav-bar title="频道管理">
        <template #right>
          <van-icon name="cross" size="14" color="white" @click="show = false" />
        </template>
      </van-nav-bar>

      <!-- 弹出层的主体区域 -->
      <div class="pop-body">
        <!-- 我的频道 -->
        <div class="my-channel-box">
          <div class="channel-title">
            <span>
              <span class="title-bold">我的频道：</span>
              <span class="title-gray">点击进入频道</span>
            </span>
            <span class="btn-edit" @click="isEdit = !isEdit">{{isEdit ? '完成' : '编辑'}}</span>
          </div>
          <!-- 我的频道列表 -->
          <van-row type="flex">
            <van-col span="6" v-for="item in channels" :key="item.id">
              <div class="channel-item van-hairline--surround" @click="onChannelRemove(item)">
                {{item.name}}
                <!-- 删除的徽标 -->
                <van-badge color="transparent" class="cross-badge" v-if="isEdit && item.name !== '推荐'">
                  <template #content>
                    <van-icon name="cross" class="badge-icon" color="#cfcfcf" size="12" />
                  </template>
                </van-badge>
              </div>
            </van-col>
          </van-row>
        </div>

        <!-- {{channels.length}} -->

        <van-divider></van-divider>

        <!-- 更多频道 -->
        <div class="more-channel-box">
          <div class="channel-title">
            <span>
              <span class="title-bold">可添加频道：</span>
              <span class="title-gray">点击添加频道</span>
            </span>
          </div>
          <!-- 更多频道列表 -->
          <van-row type="flex">
            <van-col span="6" v-for="item in moreChannels" :key="item.id">
              <div class="channel-item van-hairline--surround" @click="addChannel(item)">{{item.name}}</div>
            </van-col>
          </van-row>
        </div>
      </div>
    </div>
  </van-popup>
</template>

<script>
import { getChannelList, getAllChannels, updateMyChannels } from '@/api/homeAPI'
import { onMounted, ref, computed } from 'vue'
import { Notify } from 'vant'
import ArtList from '@/views/Article/ArticleList.vue'

export default {
  name: 'Home',
  setup() {
    // 已关注频道的列表数据
    const channels = ref([])
    // 所有频道的列表
    const allChannels = ref([])
    // 激活项的索引
    const active = ref(0)
    // 是否展示频道管理的弹出层
    const show = ref(false)
    // 频道是否处于编辑状态
    const isEdit = ref(false)

    // 获取已关注的频道列表
    onMounted(async () => {
      const { data: res } = await getChannelList()
      if (res.message === 'OK') {
        channels.value = res.data.channels
      }
    })

    // 获取所有频道的列表
    onMounted(async () => {
      const { data: res } = await getAllChannels()
      if (res.message === 'OK') {
        allChannels.value = res.data.channels
      }
    })

    // 动态计算更多频道的列表数据
    const moreChannels = computed(() => {
      return allChannels.value.filter(x => {
        const index = channels.value.findIndex(y => x.id === y.id)
        if (index === -1) return true
      })
    })

    // 更新后端的频道列表数据
    const updateChannels = async () => {
      const data = {
        channels: channels.value
          .filter(x => x.name !== '推荐')
          .map((x, i) => ({
            id: x.id, // 频道的 Id
            seq: i + 1 // 频道的序号（给后端排序用的）
          }))
      }

      const { data: res } = await updateMyChannels(data)

      if (res.message === 'OK') {
        // 3. 通过 notify 弹框提示用户更新成功
        Notify({
          type: 'success',
          message: '更新成功！',
          duration: 1000
        })
      }
    }

    // 点击移除频道
    const onChannelRemove = item => {
      if (!isEdit.value) return
      if (item.name === '推荐') return
      channels.value = channels.value.filter(x => x.id !== item.id)
      updateChannels()
    }

    // 点击新增频道
    const addChannel = async item => {
      // Bug：直接向频道数组中 push 新频道，页面不会刷新
      channels.value.push(item)
      await updateChannels()
      // Bug：在每次新增频道之后，重新请求频道列表数据才行
      const { data: res } = await getChannelList()
      if (res.message === 'OK') {
        channels.value = res.data.channels
      }
    }

    return {
      channels,
      active,
      show,
      moreChannels,
      isEdit,
      onChannelRemove,
      addChannel
    }
  },
  components: {
    ArtList
  }
}
</script>

<style lang="less" scoped>
.home-container {
  padding-top: 46px;
  padding-bottom: 50px;
}

.logo {
  height: 80%;
}

// 设置 tabs 容器的样式
/deep/ .van-tabs__wrap {
  padding-right: 30px;
  background-color: #fff;
}

// 设置小图标的样式
.moreChannels {
  position: fixed;
  top: 62px;
  right: 8px;
  z-index: 999;
}

.popup-container {
  display: flex;
  flex-direction: column;
}

.pop-header {
  height: 90px;
  background-color: #007bff;
  color: white;
  text-align: center;
  font-size: 14px;
  position: relative;
  .title {
    width: 100%;
    position: absolute;
    bottom: 15px;
  }
}

.pop-body {
  flex: 1;
  overflow: scroll;
  padding: 8px;
  background-color: white;
}

.my-channel-box,
.more-channel-box {
  .channel-title {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    line-height: 28px;
    padding: 0 6px;
  }
}

.channel-item {
  font-size: 12px;
  text-align: center;
  line-height: 36px;
  background-color: #fafafa;
  margin: 5px;
}

.title-bold {
  font-weight: bold;
}
.title-gray {
  font-size: 12px;
  color: gray;
}

.btn-edit {
  border: 1px solid #a3a2a2;
  font-size: 12px;
  border-radius: 4px;
  height: 20px;
  line-height: 20px;
  padding: 0px 8px;
}

.cross-badge {
  position: absolute;
  right: -3px;
  top: 0;
  border: none;
}
</style>
